#include "recbox.h"
#include "ui_recbox.h"

#include "recboxitem.h"
#include <QDebug>
#include <QJsonObject>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray objarray, int row)
{
    if(row == 2)
    {
        _row = 2;
        _col = 8;
    }
    else {

        ui->recListDown->hide();
    }

    imageList = objarray;

    //设置 默认组下标
    _currentIndex = 0;
    //设置 组个数
    _countNum = (objarray.size() / _col);

    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    //删除之前item
    QList<RecBoxItem*> recUpItemList = findChildren<RecBoxItem*>();
    for(auto item : recUpItemList)
    {
        ui->recListUpHLayout->removeWidget(item);

        delete item;
    }

    QList<RecBoxItem*> recDownItemList = findChildren<RecBoxItem*>();
    for(auto item : recDownItemList)
    {
        ui->recListUpHLayout->removeWidget(item);

        delete item;
    }

    //添加新item
    int index = 0;
    for(int i = _col * _currentIndex ; i < _col + _col * _currentIndex ; ++i)
    {
        QJsonObject obj = imageList[i].toObject();

        //新建item
        RecBoxItem* item = new RecBoxItem(this);
        //设置图片路径
        item->setImage(obj.value("path").toString());
        //设置文字
        item->setText(obj.value("text").toString());

        //添加进Layout
        if(index >= _col / 2 && _row == 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {

            ui->recListUpHLayout->addWidget(item);
        }
        index++;
    }
}

void RecBox::on_btUp_clicked()
{
    _currentIndex--;
    if(_currentIndex < 0)
    {
        _currentIndex = _countNum - 1;
    }

    createRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    _currentIndex++;
    if(_currentIndex >= _countNum)
    {
        _currentIndex = 0;
    }

    createRecBoxItem();
}
